package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ElderMapper elderMapper;

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);

        //查询老人信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        //查询入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        //转换家属列表:将string类型的json对象封装到list<ElderFamilyVo>
        List<ElderFamilyVo> elderFamilyVoList=(JSON.parseArray(elder.getRemark(), ElderFamilyVo.class));
        return new CheckInDetailVo(checkInElderVo,elderFamilyVoList,checkInConfigVo,contract);
        //String remark = elder.getRemark();

    }




    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //检验老人是否入住
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, elderDto.getIdCardNo())
                .eq(Elder::getStatus,1)
        );
        if(ObjectUtil.isNotEmpty(elder)){
            throw new RuntimeException("该老人已入住");
        }
        //更新床位状态
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);

        //新增或者更新老人
        elder= BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        Elder elder1 = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, elderDto.getIdCardNo()));
        if (ObjectUtil.isEmpty(elder1)){
            elderMapper.insert(elder);
        }else {
            elderMapper.updateById(elder);
        }
        //新增签约办理
        insertContract(dto,elder);
        //新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder, bed);
        //新增入住配置
        instrtConfig(dto,checkIn);



    }

    private CheckIn saveCheckIn(CheckInApplyDto dto,Elder elder,Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void instrtConfig(CheckInApplyDto dto,CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setRemark(dto.getElderFamilyDtoList().toString());
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private void insertContract(CheckInApplyDto dto,Elder elder) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderName(elder.getName());
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(1);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
    }


}
